/*
	Copyright (c) 2004 Cory Nelson

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gamestat.h"
#include "internal.h"

static char *qw_parsestring(char **data) {
	size_t len;

	if((*data)[0]!='\\' && (*data)[0]!='\n') return NULL;
	(*data)++;

	len=strcspn(*data, "\\\n");
	if(len > 0) {
		char *str=malloc(len+1);

		memcpy(str, *data, len);
		str[len]=0;

		(*data)+=len;
		return str;
	}
	else return NULL;
}

typedef char* (*getdata_cb)(char*); // return pointer to data if packet is valid
typedef void (*parseinfo_cb)(GS_SERVERINFO*, GS_PROPERTY*);
typedef void (*parseplayer_cb)(GS_PLAYERINFO*, char*);

static GS_SERVERINFO *__queryserver_quakeworld(const char *host, unsigned short port, const char *data, int datalen, getdata_cb getdata, parseinfo_cb parseinfo, parseplayer_cb parseplayer, unsigned char breakifnullkey) {
	SOCKET s=getsockudp(host, port);
	size_t packetlen;
	char *packet;
	GS_PLAYERINFO *curplayer=NULL;
	GS_PROPERTY *curproperty=NULL;
	GS_SERVERINFO *info;
	char *iter, *end;
	clock_t ping;

	if(s==INVALID_SOCKET) return NULL;

	ping=clock();
	if(send(s, data, datalen, 0)==SOCKET_ERROR) {
		lasterror=GS_ERROR_TIMEOUT;
		goto err;
	}
	packet=getpacket(s, &packetlen);
	if(!packet) {
		lasterror=GS_ERROR_TIMEOUT;
		goto err;
	}
	ping=clock()-ping;
	closesocket(s);

	dbg_dumpbuf("quakeworld.bin", packet, packetlen);

	iter=getdata(packet);
	if(!iter) {
		lasterror=GS_ERROR_CORRUPT;
		free(packet);
		return NULL;
	}
	end=packet+packetlen;

	info=calloc(1, sizeof(GS_SERVERINFO));
	info->ping=(int)ping;

	while(iter<end) {
		// key/value
		if(*iter == '\\') {
			char *key=qw_parsestring(&iter);

			if(key) {
				if(iter<end) {
					GS_PROPERTY *property=malloc(sizeof(GS_PROPERTY));
					property->key=key;
					property->value=qw_parsestring(&iter);
					property->next=NULL;

					if(property->value) parseinfo(info, property);
					
					if(curproperty) curproperty=curproperty->next=property;
					else curproperty=info->properties=property;
				}
				else free(key);
			}
			else if(breakifnullkey) break;
		}

		// player string
		else if(*iter == '\n') {
			char *infostr=qw_parsestring(&iter);

			if(infostr) {
				GS_PLAYERINFO *player=calloc(1, sizeof(GS_PLAYERINFO));

				parseplayer(player, infostr);
				player->time*=60;

				if(curplayer) curplayer=curplayer->next=player;
				else curplayer=info->players=player;
				info->numplayers++;

				free(infostr);
			}
			else break;
		}
		else break; // should never get here..
	}

	free(packet);

	if(!info->host || !info->map) {
		GSFreeServerInfo(info);
		lasterror=GS_ERROR_CORRUPT;
		return NULL;
	}

	lasterror=GS_OK;
	return info;

err:
	closesocket(s);
	return NULL;
}

//////////////////////////////////////////////////////////////
// QuakeWorld

typedef struct {
	int check;
	char check2;
	char data[1];
} QUAKEWORLD_STATUS_PACKET;

static char* qw_getdata(char *packet) {
	QUAKEWORLD_STATUS_PACKET *p=(QUAKEWORLD_STATUS_PACKET*)packet;

	if(swapint32(p->check)!=-1 || p->check2!='n') return NULL;
	else return p->data;
}

static void qw_parseinfo(GS_SERVERINFO *info, GS_PROPERTY *property) {
	if(!info->host && !stricmp(property->key, "hostname")) info->host=strdup(property->value);
	else if(!info->mod && !stricmp(property->key, "*gamedir")) info->mod=strdup(property->value);
	else if(!info->map && !stricmp(property->key, "map")) info->map=strdup(property->value);
	else if(!stricmp(property->key, "maxclients")) info->maxplayers=atoi(property->value);
	else if(!stricmp(property->key, "timelimit")) info->timelimit=atoi(property->value);
	else if(!stricmp(property->key, "fraglimit")) info->scorelimit=atoi(property->value);
	else if(!stricmp(property->key, "needpass")) info->passworded=atoi(property->value);
}

static void qw_parseplayer(GS_PLAYERINFO *player, char *str) {
	char name[128];

	sscanf(str, "%*d %d %d %d \"%[^\"]",
		&player->score, &player->time, &player->ping, name);
	player->name=strdup(name);
}

GS_SERVERINFO *queryserver_quakeworld(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFFstatus", 10, qw_getdata, qw_parseinfo, qw_parseplayer, 1);
}

void stripcolor_quakeworld(char *out, const char *in) {
	size_t i, len=strlen(in);
	const unsigned char *inb=(const unsigned char*)in;

	for(i=0; i<len; i++) {
		switch(inb[i]) {
			case 0x10:
			case 0x90:
				out[i]='[';
				break;
			case 0x11:
			case 0x91:
				out[i]=']';
				break;
			case 0x0A:
			case 0x0C:
			case 0x8A:
			case 0x8C:
			case 0xA0:
				out[i]=' ';
				break;
			default:
				if(inb[i] >= 0xA1 && inb[i] <= 0xFE) out[i]=inb[i]-128;
				else if(inb[i] >= 0x92 && inb[i] <= 0x9B) out[i]=inb[i]-98;
				else if(inb[i] >= 0x12 && inb[i] <= 0x1B) out[i]=inb[i]+30;
				else if(!isascii(inb[i])) out[i]='.';
		}
	}
	out[i]='\0';
}

//////////////////////////////////////////////////////////////
// Quake 2, Soldier of Fortune

typedef struct {
	int check;
	char check2[6];
	char data[1];
} QUAKE2_STATUS_PACKET;

static char* q2_getdata(char *packet) {
	QUAKE2_STATUS_PACKET *p=(QUAKE2_STATUS_PACKET*)packet;

	p->check2[5]=0;
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "print")) return NULL;
	else return p->data;
}

static void q2_parseinfo(GS_SERVERINFO *info, GS_PROPERTY *property) {
	if(!info->host && !stricmp(property->key, "hostname")) info->host=strdup(property->value);
	else if(!info->mod && !stricmp(property->key, "gamename")) info->mod=strdup(property->value);
	else if(!info->map && !stricmp(property->key, "mapname")) info->map=strdup(property->value);
	else if(!stricmp(property->key, "maxclients")) info->maxplayers=atoi(property->value);
	else if(!stricmp(property->key, "timelimit")) info->timelimit=atoi(property->value);
	else if(!stricmp(property->key, "fraglimit")) info->scorelimit=atoi(property->value);
	else if(!stricmp(property->key, "needpass")) info->passworded=atoi(property->value);
}

static void q2_parseplayer(GS_PLAYERINFO *player, char *str) {
	char name[128];

	sscanf(str, "%d %d \"%[^\"]",
		&player->score, &player->ping, name);
	player->name=strdup(name);
}

GS_SERVERINFO *queryserver_quake2(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFFstatus\n", 12, q2_getdata, q2_parseinfo, q2_parseplayer, 1);
}

GS_SERVERINFO *queryserver_sof(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFFstatus\n", 12, q2_getdata, q2_parseinfo, q2_parseplayer, 0);
}

void stripcolor_sof(char *out, const char *in) {
	const unsigned char *inb=(const unsigned char*)in;
	size_t i, pos=0, len=strlen(in);

	for(i=0; i<len; i++) if(inb[i]>=32) out[pos++]=inb[i];
	out[pos]='\0';
}

//////////////////////////////////////////////////////////////
// Quake 3, Soldier of Fortune 2

typedef struct {
	int check;
	char check2[15];
	char data[1];
} QUAKE3_STATUS_PACKET;

static char* q3_getdata(char *packet) {
	QUAKE3_STATUS_PACKET *p=(QUAKE3_STATUS_PACKET*)packet;

	p->check2[14]=0;
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "statusResponse")) return NULL;
	else return p->data;
}

static void q3_parseinfo(GS_SERVERINFO *info, GS_PROPERTY *property) {
	if(!info->host && !stricmp(property->key, "sv_hostname")) info->host=strdup(property->value);
	else if(!info->mod && (!stricmp(property->key, "gamename") || !stricmp(property->key, "g_gametypestring"))) info->mod=strdup(property->value);
	else if(!info->map && !stricmp(property->key, "mapname")) info->map=strdup(property->value);
	else if(!stricmp(property->key, "sv_maxclients")) info->maxplayers=atoi(property->value);
	else if(!stricmp(property->key, "timelimit")) info->timelimit=atoi(property->value);
	else if(!stricmp(property->key, "fraglimit")) info->scorelimit=atoi(property->value);
	else if(!stricmp(property->key, "g_needpass") || !stricmp(property->key, "pswrd")) info->passworded=atoi(property->value);
}

static void sof2_parseplayer(GS_PLAYERINFO *player, char *str) {
	char name[128];

	sscanf(str, "%d %d %*d \"%[^\"]",
		&player->score, &player->ping, name);
	player->name=strdup(name);
}

GS_SERVERINFO *queryserver_quake3(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFFgetstatus\n", 15, q3_getdata, q3_parseinfo, q2_parseplayer, 1);
}

GS_SERVERINFO *queryserver_sof2(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFFgetstatus\n", 15, q3_getdata, q3_parseinfo, sof2_parseplayer, 1);
}

void stripcolor_null(char *out, const char *in) {
	return;
}

void stripcolor_quake3(char *out, const char *in) {
	size_t i, pos=0, len=strlen(in);

	for(i=0; i<len; i++) {
		if(in[i]!='^') out[pos++]=in[i];
		else i++;
	}
	out[pos]='\0';
}

//////////////////////////////////////////////////////////////
// Medal of Honor

typedef struct {
	int check;
	char unknown; // protocol version?
	char check2[15];
	char data[1];
} MOH_STATUS_PACKET;

static char* moh_getdata(char *packet) {
	MOH_STATUS_PACKET *p=(MOH_STATUS_PACKET*)packet;

	p->check2[14]=0;
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "statusResponse")) return NULL;
	else return p->data;
}

static void moh_parseplayer(GS_PLAYERINFO *player, char *str) {
	char name[128];

	sscanf(str, "%d \"%[^\"]", &player->ping, name);
	player->name=strdup(name);
}

GS_SERVERINFO *queryserver_moh(const char *host, unsigned short port) {
	return __queryserver_quakeworld(host, port, "\xFF\xFF\xFF\xFF\x02getstatus\n", 16, moh_getdata, q3_parseinfo, moh_parseplayer, 1);
}
